import os
import shutil


class ts_megre():
    def __init__(self,path,name,threadnum):
        """
        合并类
        :param path: 下载文件路径 
        :param threadnum: 线程数
        """
        self.path = path
        self.name = name
        self.threadnum = threadnum
        self.gongzuomulu = os.getcwd()

    def build_catalog(self):
        """
        生成各线程的目录
        :return: 
        """
        path_list = []
        for i in range(self.threadnum):
            path = self.path + "\\th-" + str(i)
            path_list.append(path)
        return path_list

    def move(self,path_list:list):
        """
        移动ts
        :param path_list: 各线程目录
        :return: 
        """
        for ts in path_list:
            os.chdir(ts)
            command = "move" + " " + "*.ts" + " " + self.path
            os.system(command)
        os.chdir(self.gongzuomulu) #回到原来的工作目录

    def combine(self):
        """
        合并文件
        :return: 
        """
        os.chdir(self.path)
        os.system("type *.ts>>"+self.name+".mp4")
        os.chdir(self.gongzuomulu)  # 回到原来的工作目录

    def del_catalog(self,path_list:list):
        """
        删除各线程的目录
        :param path_list: 
        :return: 
        """
        os.chdir(self.path)
        for path in path_list:
            try:
                shutil.rmtree(path)
            except:
                print("文件未找到")
        os.chdir(self.gongzuomulu)  # 回到原来的工作目录

    def del_file(self):
        """
        删除ts文件
        :return: 
        """
        for root, dirs, files in os.walk(self.path):  # os.walk()返回元组，包含三个元素:每次遍历的路径名、路径下子目录列表、目录下文件列表
            for name in files:
                if name.endswith(".ts"):
                    os.remove(os.path.join(root, name))
        os.chdir(self.gongzuomulu)  # 回到原来的工作目录


